package com.ruangong.GitClient.app.GiteeFile;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.ruangong.GitClient.GiteeAPI.GiteeRepository;
import com.ruangong.GitClient.GiteeAPI.GiteeUser;
import com.ruangong.GitClient.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.ruangong.GitClient.GiteeAPI.GiteeUser.refreshToken;


public class GiteeViewerActivity extends AppCompatActivity {

    // 在 onCreate 方法中实例化 GiteeUser 并获取访问令牌
    GiteeUser giteeUser = new GiteeUser();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_giteeviewer);


        // 恢复数据
        SharedPreferences sharedPreferences = getSharedPreferences("app_data", Context.MODE_PRIVATE);
        giteeUser.accessToken = sharedPreferences.getString("access_token", "");
        giteeUser.refreshToken = sharedPreferences.getString("refresh_token", "");


        Log.d("GiteeUser", "转换后的数据: " + giteeUser.toString());
        String accessToken = giteeUser.getAccessToken();


        // 找到三个按钮
        ImageButton button1 = findViewById(R.id.buttonGiteeLogin);
        ImageButton button2 = findViewById(R.id.buttonGiteeRefresh);
        ImageButton button3 = findViewById(R.id.buttonGiteeRepository);

        button1.setOnClickListener(view -> {
            String clientId = "8d2ed355a3b431c98f9302ef20df0558f27616c8f3135bca58824d4f835ade43";
            String redirectUri = "myapp://callback"; // 例如：myapp://gitee_callback
            String url = "https://gitee.com/oauth/authorize?client_id=" + clientId + "&redirect_uri=" + Uri.encode(redirectUri) + "&response_type=code";
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(browserIntent);
            Log.d("OAuthLogin", "Attempting to open browser with URL: " + url);
        });


        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("GiteeUser", "转换后的数据: " + giteeUser.toString());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            refreshToken();
                        } catch (IOException e) {
                            // 处理刷新令牌时可能出现的异常
                            e.printStackTrace();

                            // 在 UI 线程中显示错误信息
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(GiteeViewerActivity.this, "刷新令牌失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();

            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (accessToken != null) {
                    // 使用异步任务来执行获取存储库信息的操作
                    new AsyncTask<Void, Void, List<GiteeRepository>>() {
                        @Override
                        protected List<GiteeRepository> doInBackground(Void... params) {
                            return giteeUser.getRepositories();
                        }

                        @Override
                        protected void onPostExecute(List<GiteeRepository> repos) {
                            if (repos != null) {
                                // 创建 Intent 对象，并将存储库信息传递给 GiteeRepositoryActivity
                                Intent intent = new Intent(GiteeViewerActivity.this, GiteeRepositoryActivity.class);
                                intent.putExtra("repositories", new ArrayList<>(repos)); // 使用ArrayList复制repos以避免序列化问题
                                startActivity(intent);
                            } else {
                                // 处理获取存储库信息失败的情况
                                Toast.makeText(GiteeViewerActivity.this, "无法获取存储库信息", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }.execute();
                } else {
                    // 处理获取AccessToken失败的情况
                    Toast.makeText(GiteeViewerActivity.this, "无法获取访问令牌", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    @Override
    protected void onPause() {
        super.onPause();

        // 保存数据到 SharedPreferences
        SharedPreferences sharedPreferences = getSharedPreferences("app_data", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("access_token", giteeUser.getAccessToken());
        editor.putString("refresh_token", giteeUser.getRefreshToken());
        editor.apply(); // 提交保存
    }

}
